package service

import (
	"cloudmusic/model"
	"encoding/json"
	"fmt"
	"github.com/henrylee2cn/pholcus/app/downloader/request"
	"github.com/henrylee2cn/pholcus/app/spider"
	"github.com/henrylee2cn/pholcus/common/goquery"
	"net/http"
	"strconv"
	"strings"
)

var TagList []string

//func init() {
//	TagList, _ = model.GetTagNameList()
//}

var Spider = &spider.Spider{
	Name:         "网易云音乐",
	Description:  "通过网易云的歌单爬取歌曲",
	EnableCookie: true,
	RuleTree: &spider.RuleTree{
		Root: func(ctx *spider.Context) {
			//for _, tagName := range TagList {
			tagName := "华语"
			ctx.AddQueue(&request.Request{
				Url:    "https://music.163.com/discover/playlist/?cat=" + tagName,
				Rule:   "get_play_list_page",
				Method: "GET",
			})
			//}

		},
		Trunk: map[string]*spider.Rule{
			"get_play_list_page": {
				ParseFunc: func(ctx *spider.Context) {
					dom := ctx.GetDom().Find("#m-disc-pl-c").Find("div.u-page a.zpgi").Last()
					pageStr := dom.Text()
					ctx.Aid(map[string]interface{}{
						"page": pageStr,
					}, "get_play_list")
				},
			},
			"get_play_list": {
				AidFunc: func(ctx *spider.Context, aid map[string]interface{}) interface{} {
					//page, _ := strconv.Atoi(aid["page"].(string))
					//for p := 0; p < page; p++ {
					p := 0
					offset := strconv.Itoa(p * 35)
					ctx.AddQueue(&request.Request{
						Url:    ctx.GetUrl() + "&limit=35&offset=" + offset,
						Rule:   "get_play_list",
						Method: "GET",
					})
					//}
					return nil
				},
				ParseFunc: func(ctx *spider.Context) {
					//dom := ctx.GetDom().Find("#m-pl-container")
					//dom.Find("li").Each(func(i int, li *goquery.Selection) {
					//	playListId, _ := li.Find("div.bottom").Find("a").Attr("data-res-id")
					playListId := "2829883282"
					ctx.AddQueue(&request.Request{
						Url:    "https://music.163.com/playlist?id=" + playListId,
						Method: "GET",
						Rule:   "get_music_list",
					})
					//})
				},
			},
			//歌曲
			//{
			//	"data": [{
			//		"id": 1436910205,
			//		"url": "http://m701.music.126.net/20200406134821/c640bf5e3eb209a7dfaf552f3f681eed/jdymusic/obj/w5zDlMODwrDDiGjCn8Ky/2035472537/417a/aa27/1a29/2a3d0fedc06ea44a7308c08c7e3436c5.mp3",
			//		"br": 128000,
			//		"size": 4204077,
			//		"md5": "2a3d0fedc06ea44a7308c08c7e3436c5",
			//		"code": 200,
			//		"expi": 1200,
			//		"type": "mp3",
			//		"gain": 0.0,
			//		"fee": 0,
			//		"uf": null,
			//		"payed": 0,
			//		"flag": 64,
			//		"canExtend": false,
			//		"freeTrialInfo": null,
			//		"level": "standard",
			//		"encodeType": "mp3"
			//	}],
			//	"code": 200
			//}
			"get_music_list": {
				ParseFunc: func(ctx *spider.Context) {
					ctx.GetDom().Find("#song-list-pre-cache").Find("ul").Find("li").Each(func(i int, li *goquery.Selection) {
						href, _ := li.Find("a").Attr("href")
						songUrlJson := make(map[string]interface{})
						songDetailJson := make(map[string]interface{})
						arr := strings.Split(href, "=")
						id := arr[1]
						//获取歌曲详情
						songDetail, _ := GetSongDetail("[" + id + "]")
						_ = json.Unmarshal([]byte(songDetail), &songDetailJson)
						fmt.Println(songDetailJson)
						//获取歌曲的路径
						res, _ := GetSongUrl("["+id+"]", "128000")
						_ = json.Unmarshal([]byte(res), &songUrlJson)
						data := songUrlJson["data"].([]interface{})[0].(map[string]interface{})
						if data["code"].(float64) == 200 {
							ext, contentType := GetContentType(data["url"].(string))
							rec, _ := http.Get(data["url"].(string))
							fmt.Println(li.Find("a").Text())
							file := FileIO{
								ObjectName:  li.Find("a").Text() + "." + ext,
								FileReader:  rec.Body,
								Type:        0,
								ContentType: contentType,
								BucketName:  ext,
								Size:        int64(data["size"].(float64)),
							}
							FileUploadChan <- file
						}
					})
				},
			},
		},
	},
}

var CatSpider = &spider.Spider{
	Name:         "网易云音乐标签",
	Description:  "获取网易云音乐的标签",
	EnableCookie: true,
	RuleTree: &spider.RuleTree{
		Root: func(ctx *spider.Context) {
			ctx.AddQueue(&request.Request{
				Url:    "https://music.163.com/discover/playlist",
				Rule:   "get_cat",
				Method: "GET",
			})
		},
		Trunk: map[string]*spider.Rule{
			"get_cat": {
				ParseFunc: func(ctx *spider.Context) {
					dom := ctx.GetDom().Find("#cateListBox").Find("div.bd").Find("dl.f-cb")
					dom.EachWithBreak(func(i int, q *goquery.Selection) bool {
						dt := q.Find("dt").Text()
						p_tag := model.Tags{
							Pid:     0,
							TagName: dt,
						}
						pid, err := p_tag.InsertGetID()
						if err != nil {
							return false
						}
						q.Find("dd a").Each(func(i int, a *goquery.Selection) {
							dd, _ := a.Attr("data-cat")
							tag := model.Tags{
								TagName: dd,
								Pid:     pid,
							}
							_, _ = tag.InsertGetID()
						})
						return true
					})
				},
			},
		},
	},
}
